import {useEffect, useState} from 'react';
import { listTree } from '@/services/system/dept';
import { treeDataWrapper } from '@/utils/common';
import { Tree } from 'antd';

const SystemDeptTree = (props) => {
  const {onSelect} = props;

  const [treeData, handleTreeData] = useState([]);
  const [selectData, handleSelectData] = useState(null);

  useEffect( () => {
    const lostData = async () => {
      const response = await listTree();
      const listData = Array.isArray(response.data) ? response.data : [];

      return listData;
    };

    lostData().then((listData) =>{
      treeDataWrapper(listData);
      handleTreeData(listData);

      if (listData.length > 0) {
        handleSelectData(listData[0]);
        onSelect(listData[0]);
      }
    });
  }, []);

  const handleSelect = (selectedKeys, { selected, node }) => {
    if (selected) {
      handleSelectData(node);
      onSelect(node);
    }
  }

  return (
    <Tree 
      treeData={treeData} 
      selectedKeys={[selectData ? selectData.id : null]}
      onSelect={handleSelect}
    />
  );
}

export default SystemDeptTree;